<?php
namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Session;
use think\facade\View;

class Base extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->initialize();
    }
    
    protected function initialize()
    {
        // 检查管理员登录状态
        if (!$this->checkAuth()) {
            if ($this->request->isAjax()) {
                echo json_encode(['code' => 0, 'msg' => '请先登录', 'url' => '/admin/login']);
                exit;
            }
            header('Location: /admin/login');
            exit;
        }
        
        // 设置公共视图变量
        $adminUser = Session::get('admin_user');
        if ($adminUser) {
            View::assign('admin_user', $adminUser);
        }
    }
    
    protected function checkAuth()
    {
        // 获取控制器和方法名
        $controller = $this->request->controller();
        $action = $this->request->action();
        
        // 登录相关页面不需要验证
        if ($controller == 'Login') {
            return true;
        }
        
        // 检查session中是否有管理员信息
        return Session::has('admin_user');
    }
    
    /**
     * 成功响应
     */
    protected function success($msg = '操作成功', $url = null, $data = '', $wait = 3)
    {
        if ($this->request->isAjax()) {
            return json([
                'code' => 1,
                'msg' => $msg,
                'data' => $data,
                'url' => $url,
                'wait' => $wait
            ]);
        }
        
        return view('success', [
            'msg' => $msg,
            'url' => $url,
            'data' => $data,
            'wait' => $wait
        ]);
    }
    
    /**
     * 错误响应
     */
    protected function error($msg = '操作失败', $url = null, $data = '', $wait = 3)
    {
        if ($this->request->isAjax()) {
            return json([
                'code' => 0,
                'msg' => $msg,
                'data' => $data,
                'url' => $url,
                'wait' => $wait
            ]);
        }
        
        return view('error', [
            'msg' => $msg,
            'url' => $url,
            'data' => $data,
            'wait' => $wait
        ]);
    }
    
    /**
     * 分页数据响应 (用于layui table)
     */
    protected function layuiData($data, $count = 0, $msg = '', $code = 0)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'count' => $count,
            'data' => $data
        ]);
    }
}
